package com.zsrt.tmall.user.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.zsrt.tmall.phone.dao.PhoneDao;
import com.zsrt.tmall.user.dao.UserDao;
import com.zsrt.tmall.user.exception.UserException;
import com.zsrt.tmall.user.service.UserService;


@Service
public class UserServiceImpl implements UserService {
	
	
	
	@Autowired
	private UserDao userDao;
	
	
	@Autowired
	private PhoneDao phoneDao;
	

	@Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.READ_UNCOMMITTED,timeout=2)
	@Override
	public int buybuy(int iphoneId, int huaweiId,String username) {
		
		
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		//0 查询价格
		int iphone = phoneDao.findPriceById(iphoneId);
		int huawei = phoneDao.findPriceById(huaweiId);
		
		
		//产品的总价格 totalPrice 
		int totalPrice =  iphone +  huawei;
		
		
		//增加1个判断  自己的钱>=totalPrice才能购买
		
		int money = userDao.findMoneyByUsername(username);
		
		
		//判断钱
		if(money < totalPrice){
			//不能买  正确的做法
			throw new UserException("余额不足，请先充值...");
		}
		
		//1  钱要减少  tmall_user_t
		//int totalPrice,String username
		
		
		//判断库存>=1
		Map<String, Object> map  = new HashMap<String, Object>();
		
		map.put("totalPrice", totalPrice);
		map.put("username", username);
		
		
		userDao.updateBalance(map);
		
		//2 库存也要减少 tmall_phone_t
		phoneDao.updateStock();
		
		System.out.println("成功购买商品....");
		
		return 0;
	}

}
